package com.edu.vocstudy;

import android.view.*;
import android.widget.*;
import android.app.*;

public class ListMenu extends ArrayAdapter<ListMenuItem> {	
	protected ListMenuItem[] menuItems_ = null;
	protected Activity context_ = null;
	
	public ListMenu(Activity context, ListMenuItem[] menuItems) {
		super(context, R.layout.list_menu_entry, R.id.entry_main_text, menuItems);
		this.menuItems_ = menuItems;
		this.context_ = context;
	}
	
	@Override
	public View getView(int position, View convertView, ViewGroup parent) {
		View row = convertView;
		ViewWrapper wrapper = null;
		
		// If we are not provided with previously used view, we need to create a new one.
		if (row == null) {
			row = super.getView(position, convertView, parent);
			wrapper = new ViewWrapper(row);
			row.setTag(wrapper);
		} else {
			wrapper = (ViewWrapper)row.getTag();
		}
		
		// The menu item object.
		ListMenuItem item = menuItems_[position];
		
		// Set the main text.
		String mainText = item.getMainText();
		if (mainText != null) {
			wrapper.getMainTextView().setText(mainText);
		}
		
		// Sub-text.
		String subText = item.getSubText();
		if (subText != null) {
			wrapper.getSubTextView().setText(subText);
		}
		
		// Menu item icon.
		int icon = item.getIcon();
		if (icon >= 0) {
			wrapper.getIconView().setImageResource(icon);
		}
		
		return row;
	}
	
	private class ViewWrapper {
		private View base_ = null;
		private TextView mainTextView_ = null;
		private TextView subTextView_ = null;
		private ImageView iconView_ = null;
		
		public ViewWrapper(View base) {
			this.base_ = base;
		}
		
		public TextView getMainTextView() {
			if (mainTextView_ == null) {
				mainTextView_ = (TextView)base_.findViewById(R.id.entry_main_text); 
			}
			return mainTextView_;
		}
		
		public TextView getSubTextView() {
			if (subTextView_ == null) {
				subTextView_ = (TextView)base_.findViewById(R.id.entry_sub_text); 
			}
			return subTextView_;
		}
		
		public ImageView getIconView() {
			if (iconView_ == null) {
				iconView_ = (ImageView)base_.findViewById(R.id.entry_icon); 
			}
			return iconView_;
		}
	}
}
